<template>
  <el-card class="main-card">
    <div class="title">{{ this.$route.name }}</div>
    <!-- 表格操作 -->
    <div class="operation-container">
      <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="openModel(null)"
      >
        新增
      </el-button>
      <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          :disabled="courseIdList.length == 0"
          @click="openDelete = true"
      >
        批量删除
      </el-button>
      <!-- 条件筛选 -->
      <div style="margin-left:auto">
        <!-- 课程类型 -->
        <el-select
            clearable
            v-model="categoryId"
            placeholder="请选择课程类型"
            size="small"
            style="margin-right:1rem;width: 180px;"
        >
          <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
          />
        </el-select>
        <!-- 课程名 -->
        <el-input
            clearable
            v-model="keywords"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="请输入课程名"
            style="width:200px"
            @keyup.enter.native="searchCourses"
        />
        <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            style="margin-left:1rem"
            @click="searchCourses"
        >
          搜索
        </el-button>
      </div>
    </div>
    <!-- 表格展示 -->
    <el-table
        border
        :data="courseList"
        @selection-change="selectionChange"
        v-loading="loading"
    >
      <!-- 表格列 -->
      <el-table-column type="selection" width="55"/>
      <el-table-column
          prop="courseCover"
          label="课程封面"
          width="180"
          align="center"
      >
        <template slot-scope="scope">
          <el-image
              class="course-cover"
              :src="
              scope.row.courseCover
                ? scope.row.courseCover
                : 'https://static.talkxj.com/articles/c5cc2b2561bd0e3060a500198a4ad37d.png'
            "
          />
          <i class="iconfont el-icon-mygongkai movie-status-icon"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名字" align="center"/>
      <el-table-column
          prop="categoryName"
          label="分类"
          width="110"
          align="center"
      />
      <el-table-column prop="isFree" label="是否免费" width="110" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isFree==='0'">否</el-tag>
          <el-tag v-else-if="scope.row.isFree==='1'" type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isTop" label="是否推荐" width="110" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isTop==='0'">否</el-tag>
          <el-tag v-else-if="scope.row.isTop==='1'" type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="money" label="价格" width="70" align="center"/>
      <el-table-column
          prop="createTime"
          label="发布时间"
          width="130"
          align="center"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" style="margin-right:5px"/>
          {{ scope.row.createTime | date }}
        </template>
      </el-table-column>
      <!-- 列操作 -->
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
              type="primary"
              size="mini"
              @click="openModel(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left:10px"
              @confirm="deleteCourses(scope.row.id)"
          >
            <el-button size="mini" type="danger" slot="reference">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        class="pagination-container"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="current"
        :page-size="size"
        :total="count"
        :page-sizes="[10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
    />
    <!-- 批量逻辑删除对话框 -->
    <el-dialog :visible.sync="openDelete" width="30%">
      <div class="dialog-title-container" slot="title">
        <i class="el-icon-warning" style="color:#ff9900"/>提示
      </div>
      <div style="font-size:1rem">是否删除选中项？</div>
      <div slot="footer">
        <el-button @click="openDelete = false">取 消</el-button>
        <el-button type="primary" @click="deleteCourses(null)">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加编辑对话框 -->
    <el-dialog :visible.sync="addOrEdit" width="30%">
      <div class="dialog-title-container" slot="title" ref="courseTitle"/>
      <el-form label-width="80px" size="medium" :model="courseForm">
        <el-form-item label="课程名">
          <el-input placeholder="请输入课程名" v-model="courseForm.name" style="width:220px"/>
        </el-form-item>
        <!-- 课程分类 -->
        <el-form-item label="课程分类">
          <el-tag
              type="success"
              v-show="courseForm.categoryName"
              style="margin:0 1rem 0 0"
              :closable="true"
              @close="removeCategory"
          >
            {{ courseForm.categoryName }}
          </el-tag>
          <!-- 分类选项 -->
          <el-popover
              placement="bottom-start"
              width="460"
              trigger="click"
              v-if="!courseForm.categoryName"
          >
            <div class="popover-title">分类</div>
            <!-- 搜索框 -->
            <el-autocomplete
                style="width:100%"
                v-model="categoryName"
                :fetch-suggestions="searchCategories"
                placeholder="请输入分类名搜索，enter可添加自定义分类"
                :trigger-on-focus="false"
                @keyup.enter.native="saveCategory"
                @select="handleSelectCategories"
            >
              <template slot-scope="{ item }">
                <div>{{ item.categoryName }}</div>
              </template>
            </el-autocomplete>
            <!-- 分类 -->
            <div class="popover-container">
              <div
                  v-for="item of categoryList"
                  :key="item.id"
                  class="category-item"
                  @click="addCategory(item)"
              >
                {{ item.categoryName }}
              </div>
            </div>
            <el-button type="success" plain slot="reference" size="small">
              添加分类
            </el-button>
          </el-popover>
        </el-form-item>
        <el-form-item label="上传封面">
          <el-upload
              class="upload-cover"
              drag
              action="/api/admin/articles/images"
              multiple
              :before-upload="beforeUpload"
              :on-success="uploadCover"
          >
            <i class="el-icon-upload" v-if="courseForm.courseCover == ''"/>
            <div class="el-upload__text" v-if="courseForm.courseCover == ''">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <img v-else :src="courseForm.courseCover" width="360px" height="180px"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入简介"
              v-model="courseForm.content">
          </el-input>
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-select
              clearable
              v-model="courseForm.isTop"
              placeholder="请选择"
              size="small"
              style="margin-right:1rem;width: 180px;"
          >
            <el-option
                v-for="item in modeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-select
              clearable
              v-model="courseForm.isFree"
              placeholder="请选择"
              size="small"
              style="margin-right:1rem;width: 180px;"
          >
            <el-option
                v-for="item in modeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" v-show="courseForm.isFree==='0'">
          <el-input-number v-model="courseForm.money" controls-position="right" :precision="2" :min="0" :max="100000"></el-input-number>
        </el-form-item>
        <el-form-item label="课程" prop="url">
          <!--          <el-upload
                        v-model="courseForm.url"
                        class="upload-demo"
                        drag
                        action="/api/admin/articles/import"
                        multiple>
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                      <div class="el-upload__tip" slot="tip">只能上传mp4文件，且不超过500mb</div>
                    </el-upload>-->
          <file-upload v-model="courseForm.url"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEdit = false">取 消</el-button>
        <el-button type="primary" @click="addOrEditCourse">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import * as imageConversion from "image-conversion";

export default {
  created() {
    this.listCourses();
    this.listCategories();
  },
  data: function () {
    return {
      loading: true,
      addOrEdit: false,
      courseList: [],
      courseIdList: [],
      categoryList: [],
      categoryName: "",
      keywords: null,
      categoryId: null,
      openDelete: false,
      isDelete: 0,
      current: 1,
      size: 10,
      count: 0,
      courseForm: {
        id: null,
        name: null,
        courseCover: "",
        viewsCount: 0,
        categoryName: ""
      },
      modeList: [{code: '1', name: "是"}, {code: '0', name: "否"}],
    };
  },
  methods: {
    selectionChange(courseList) {
      this.courseIdList = [];
      courseList.forEach(item => {
        this.courseIdList.push(item.id);
      });
    },
    searchCourses() {
      this.current = 1;
      this.listCourses();
    },
    openModel(course) {
      this.courseForm = {courseCover: '', categoryName: "", viewsCount: 0,}
      if (course != null) {
        this.courseForm = JSON.parse(JSON.stringify(course));
        this.$refs.courseTitle.innerHTML = "修改课程";
      } else {
        this.courseForm.id = null;
        this.courseForm.categoryName = "";
        this.$refs.courseTitle.innerHTML = "添加课程";
      }
      this.addOrEdit = true;
    },
    deleteCourses(id) {
      var param = {};
      if (id == null) {
        param = {data: this.courseIdList};
      } else {
        param = {data: [id]};
      }
      this.axios.delete("/api/admin/courses", param).then(({data}) => {
        if (data.flag) {
          this.$notify.success({
            title: "成功",
            message: data.message
          });
          this.listcourses();
        } else {
          this.$notify.error({
            title: "失败",
            message: data.message
          });
        }
        this.openDelete = false;
      });
    },
    sizeChange(size) {
      this.size = size;
      this.listCourses();
    },
    currentChange(current) {
      this.current = current;
      this.listCourses();
    },
    listCourses() {
      this.axios
          .get("/api/admin/courses/list", {
            params: {
              current: this.current,
              size: this.size,
              keywords: this.keywords,
              categoryId: this.categoryId,
              tagId: this.tagId,
              isDelete: this.isDelete,
            }
          })
          .then(({data}) => {
            this.courseList = data.data.recordList;
            this.count = data.data.count;
            this.loading = false;
          });
    },
    listCategories() {
      this.axios.get("/api/admin/categories/search", {
        params: {type: "1"}
      }).then(({data}) => {
        this.categoryList = data.data;
      });
    },
    addOrEditCourse() {
      if (this.courseForm.name.trim() == "") {
        this.$message.error("课程名不能为空");
        return false;
      }
      if (this.courseForm.categoryName.trim() == "") {
        this.$message.error("课程类型不能为空");
        return false;
      }
      this.axios
          .post("/api/admin/course", this.courseForm)
          .then(({data}) => {
            if (data.flag) {
              this.$notify.success({
                title: "成功",
                message: data.message
              });
              this.listCourses();
            } else {
              this.$notify.error({
                title: "失败",
                message: data.message
              });
            }
            this.addOrEdit = false;
          });
    },
    searchCategories(keywords, cb) {
      this.axios
          .get("/api/admin/categories/search", {
            params: {
              keywords: keywords,
              type: "1"
            }
          })
          .then(({data}) => {
            cb(data.data);
          });
    },
    handleSelectCategories(item) {
      this.addCategory({
        categoryName: item.categoryName,
      });
    },
    saveCategory() {
      if (this.categoryName.trim() != "") {
        this.addCategory({
          categoryName: this.categoryName
        });
        this.categoryName = "";
      }
    },
    addCategory(item) {
      this.courseForm.categoryName = item.categoryName;
    },
    removeCategory() {
      this.courseForm.categoryName = null;
    },
    uploadCover(response) {
      this.courseForm.courseCover = response.data;
    },
    beforeUpload(file) {
      return new Promise(resolve => {
        if (file.size / 1024 < this.config.UPLOAD_SIZE) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion
            .compressAccurately(file, this.config.UPLOAD_SIZE)
            .then(res => {
              resolve(res);
            });
      });
    },
  },
  watch: {
    categoryId() {
      this.current = 1;
      this.listCourses();
    },
    openDelete() {
      this.current = 1;
      this.listCourses();
    }
  }
};
</script>

<style scoped>
.operation-container {
  margin-top: 1.5rem;
}

.course-status-menu span {
  margin-right: 24px;
}

.course-cover {
  position: relative;
  width: 100%;
  height: 90px;
  border-radius: 4px;
}

.course-cover::after {
  content: "";
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.course-status-icon {
  color: #fff;
  font-size: 1.5rem;
  position: absolute;
  right: 1rem;
  bottom: 1.4rem;
}

.popover-title {
  margin-bottom: 1rem;
  text-align: center;
}

.popover-container {
  margin-top: 1rem;
  height: 260px;
  overflow-y: auto;
}

.category-item {
  cursor: pointer;
  padding: 0.6rem 0.5rem;
}

.category-item:hover {
  background-color: #f0f9eb;
  color: #67c23a;
}

</style>
